import { Injectable, UnauthorizedException, NotFoundException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
import { FileStorageService } from '../shared/file-storage.service';
import { CreateUserDto, LoginDto } from './dto/user.dto';

@Injectable()
export class UserService {
  private readonly USERS_FILE = 'data/users.json';
  private readonly FAMILIES_FILE = 'data/families.json';

  constructor(
    private readonly fileStorage: FileStorageService,
    private readonly jwtService: JwtService,
  ) {}

  async createUser(createUserDto: CreateUserDto) {
    const { users } = await this.fileStorage.readJsonFile(this.USERS_FILE);
    
    // 检查邮箱是否已存在
    if (users.some(user => user.email === createUserDto.email)) {
      throw new UnauthorizedException('邮箱已被注册');
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(createUserDto.password, 10);
    
    const newUser = {
      id: Date.now().toString(),
      email: createUserDto.email,
      password: hashedPassword,
      name: createUserDto.name,
      familyId: createUserDto.familyId,
      createdAt: new Date().toISOString(),
    };

    users.push(newUser);
    await this.fileStorage.writeJsonFile(this.USERS_FILE, { users });

    // 返回用户信息（不包含密码）
    const { password, ...result } = newUser;
    return result;
  }

  async login(loginDto: LoginDto) {
    const { users } = await this.fileStorage.readJsonFile(this.USERS_FILE);
    const user = users.find(u => u.email === loginDto.email);
    console.log(users, 'users');
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }

    const isPasswordValid = await bcrypt.compare(loginDto.password, user.password);
    if (!isPasswordValid) {
      throw new UnauthorizedException('密码错误');
    }

    // 生成 JWT token
    const payload = { sub: user.id, email: user.email, familyId: user.familyId };
    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        familyId: user.familyId,
      },
    };
  }

  async getUserById(id: string) {
    const { users } = await this.fileStorage.readJsonFile(this.USERS_FILE);
    const user = users.find(u => u.id === id);
    
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const { password, ...result } = user;
    return result;
  }

  async updateUserFamily(userId: string, familyId: string) {
    const { users } = await this.fileStorage.readJsonFile(this.USERS_FILE);
    const userIndex = users.findIndex(u => u.id === userId);
    
    if (userIndex === -1) {
      throw new NotFoundException('用户不存在');
    }
  
    const { families } = await this.fileStorage.readJsonFile(this.FAMILIES_FILE);
    const familyIndex = families.findIndex(family => family.id === familyId);
  
    if (familyIndex === -1) {
      throw new Error('家庭不存在');
    }

    users[userIndex].familyId = familyId;
    await this.fileStorage.writeJsonFile(this.USERS_FILE, { users });

    const { password, ...result } = users[userIndex];
    return result;
  }
}
